package org.neframework.webtest.interceptor.ext;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.neframework.webtest.base.BaseController;
import com.tmsps.neframework.core.utils.ChkTools;
import com.tmsps.neframework.mvc.annotation.RequestMapping;
import com.tmsps.neframework.mvc.core.NeBaseController;
import com.tmsps.neframework.mvc.web.interceptor.Interceptor;

/**
 * extjs 架构处理拦截器
 * 
 * @author Administrator
 *
 */
@RequestMapping("/")
public class ExtInterceptor implements Interceptor {

	@Override
	public boolean before(NeBaseController action, Method method,
			HttpServletRequest request, HttpServletResponse response) {
		BaseController baseAction = (BaseController) action;
		// 排序
		setSortParams(baseAction, request);

		// 设置 分页 页码
		String pageNo = request.getParameter("page");
		if(ChkTools.isNotNull(request.getParameter("page.pageNum"))){
			pageNo = request.getParameter("page.pageNum");
		}
		String limit = request.getParameter("limit");
		baseAction.page.setPageNum(ChkTools.getInteger(pageNo));
		baseAction.page.setPageSize(ChkTools.getInteger(limit));

		action.result.put("page", baseAction.page);

		return true;
	}

	@Override
	public boolean after(NeBaseController action, Method method,
			HttpServletRequest request, HttpServletResponse response) {
		BaseController baseAction = (BaseController) action;

		request.setAttribute("page", baseAction.page);
		return true;
	}

	// 设置分页
	public void setSortParams(BaseController baseAction, HttpServletRequest req) {
		String sort_params_json = req.getParameter("sort");

		if (ChkTools.isNotNull(sort_params_json)) {
			JSONArray sorts = (JSONArray) JSONObject.parse(sort_params_json);
			for (Object sortParams : sorts) {
				JSONObject obj = (JSONObject) sortParams;
				baseAction.sort_params.put(obj.getString("property"),
						obj.getString("direction"));
			}
			// 设置排序字段
			// baseAction.sort_params.put("table", "t");
		}

	}

}
